package com.atguigu.spzx.user.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.common.exception.SpzxException;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.user.service.SmsService;
import com.atguigu.spzx.util.HttpUtils;
import com.atguigu.spzx.util.RegexValidateUtils;
import jakarta.annotation.Resource;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class SmsServiceImpl implements SmsService {
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Override
    public void sendCode(String phone) {
        //1、校验手机号格式
        boolean checkCellphone = RegexValidateUtils.checkCellphone(phone);
        if(!checkCellphone){
            throw new SpzxException(ResultCodeEnum.MOBILE_ERROR , null);
        }
        //2、校验手机号获取验证码的频率： 1分钟内只能获取一次、一天只能获取3次
        if(stringRedisTemplate.hasKey("user:sms:limit:"+phone)){
            throw new SpzxException(ResultCodeEnum.SMS_LIMIT_ERROR , null);
        }
        String countStr = stringRedisTemplate.opsForValue().get("user:sms:count:" + phone);
        if(!StringUtils.isEmpty(countStr) && Integer.parseInt(countStr)>=3){
            throw new SpzxException(ResultCodeEnum.SMS_COUNT_ERROR , null);
        }
        //3、发送短信： 将验证码缓存到redis中   更新获取验证码的频率
        String host = "https://dfsns.market.alicloudapi.com";
        String path = "/data/send_sms";
        String method = "POST";
        String appcode = "8e45699f00ff4bdbb807664045acd813";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        String numbers = RandomUtil.randomNumbers(4);
        bodys.put("content", "code:"+numbers+",expire_at:10");
        bodys.put("template_id", "CST_qozfh101");
        bodys.put("phone_number", phone);

        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            //获取响应体json
            String json = EntityUtils.toString(response.getEntity());
            Map map = JSON.parseObject(json, Map.class);
            if(map.get("status")==null || !"OK".equals(map.get("status"))){
                throw new SpzxException(ResultCodeEnum.ERROR , null);
            }
            //短信发送成功  将验证码缓存到redis中   更新获取验证码的频率
            stringRedisTemplate.opsForValue().set("user:sms:code:"+phone , numbers ,
                    10, TimeUnit.MINUTES);
            //一分钟只能获取一次
            stringRedisTemplate.opsForValue().set("user:sms:limit:"+phone,"1" , 2, TimeUnit.MINUTES);
            //一天只能获取3次: 更新获取验证码的次数
            Long increment = stringRedisTemplate.opsForValue().increment("user:sms:count:" + phone);
            if(increment.intValue()==1){
                //第一次获取验证码成功  设置过期时间
                stringRedisTemplate.expire("user:sms:count:" + phone ,
                        1,TimeUnit.DAYS);
            }

        } catch (Exception e) {
//            e.printStackTrace();
            throw new SpzxException(ResultCodeEnum.SMS_SEND_ERROR , e);
        }
    }
}
